﻿using Biz.Buffer;
using Biz.EF.Platform.SG;
using Biz.Process.Entity;
using Hjt212Parser;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Biz.Process
{
    public static class Processor2031
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(Processor2031));
        private static readonly List<string> ExistTable = new List<string>();
        public static void ProcessToMonitorTable(string content)
        {
            Log.Info("处理开始：2031->实时监控表(所有企业一套实时监控主从表).");
            try
            {
                if (ProcessorHelper.IsLossInfoOfCmd(content, out var mn, out var datatime, out var port, out var codes))
                {
                    return;
                }

                using (var pCtx = new PlatformXpfContext())
                {
                    var masterMonitor = pCtx.主实时监控
                        .Where(t => t.企业基本信息ID == port.企业基本信息ID)
                        .FirstOrDefault(t => t.企业排口ID == port.ID);
                    if (masterMonitor == null)
                    {
                        masterMonitor = new 主实时监控();
                        masterMonitor.企业基本信息ID = port.企业基本信息ID;
                        masterMonitor.企业排口ID = port.ID;
                        pCtx.主实时监控.Add(masterMonitor);
                    }
                    if (codes.Contains("B01") || codes.Contains("w00000"))
                    {
                        masterMonitor.污染物类别ID = 2;

                        masterMonitor.日排放量 = codes.Contains("B01") ? Parser.GetDoubleByKey("B01-Cou", content) : Parser.GetDoubleByKey("w00000-Cou", content);
                    }
                    else if (codes.Contains("B02") || codes.Contains("a00000"))
                    {
                        masterMonitor.污染物类别ID = 1;
                        masterMonitor.日排放量 = codes.Contains("B02") ? Parser.GetDoubleByKey("B01-Cou", content) : Parser.GetDoubleByKey("w00000-Cou", content);
                    }
                    else
                    {
                        masterMonitor.污染物类别ID = 2;
                        masterMonitor.日排放量 = null;
                    }
                    masterMonitor.日数据时间 = datatime;
                    masterMonitor.在线状态ID = 1201;
                    masterMonitor.在线状态时间 = DateTime.Now;
                    pCtx.SaveChanges();

                    ProcessorHelper.RemoveMasterFactor(codes, true);

                    foreach (var code in codes)
                    {
                        var contam = CommonInformation.GetContamCode(code);
                        if (contam == null)
                        {
                            continue;
                        }

                        var detailMonitor = masterMonitor.从实时监控.FirstOrDefault(t => t.污染物编码ID == contam.ID);
                        if (detailMonitor == null)
                        {
                            detailMonitor = new 从实时监控();
                            detailMonitor.污染物编码ID = contam.ID;
                            masterMonitor.从实时监控.Add(detailMonitor);
                        }
                        detailMonitor.日排放量 = Parser.GetDoubleByKey(code + "-Cou", content);
                    }
                    pCtx.SaveChanges();

                }
            }
            catch (Exception ex)
            {
                Log.Error(ex + Environment.NewLine + content);
            }
            Log.Info("处理结束：2031->实时监控表(所有企业一套实时监控主从表).");

        }

        public static void ProcessToWechatSingleTablePerEnterprise(string content)
        {
            Log.Info("处理开始：2031->日数据(每个企业一套日主从表).");
            string sql = "";
            try
            {
                if (ProcessorHelper.IsLossInfoOfCmd(content, out var mn, out var datatime, out var port, out var codes))
                {
                    return;
                }
                var eCode = CommonInformation.GetPollutionSourceCodeByMn(mn);
                if (string.IsNullOrWhiteSpace(eCode)) return;

                using (var pCtx = new PlatformXpfContext())
                {
                    var tableName = "主日数据_企业ID".Replace("_企业ID", "_" + eCode);
                    int? count;
                    if (!ExistTable.Contains(tableName))
                    {
                        count = pCtx.Database.SqlQuery<int?>(Cmd2031Sqls.M_EXIST.Replace("_企业ID", "_" + eCode)).FirstOrDefault();
                        if (!count.HasValue || count < 1)
                        {
                            pCtx.Database.ExecuteSqlCommand(Cmd2031Sqls.M_CREATE.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2031Sqls.M_ALTER_1.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2031Sqls.M_ALTER_2.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2031Sqls.M_NONCLUSTERED_1.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2031Sqls.M_NONCLUSTERED_2.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2031Sqls.M_NONCLUSTERED_3.Replace("_企业ID", "_" + eCode));
                        }
                        ExistTable.Add(tableName);
                    }
                    Master master = new Master();

                    master.enterpriseId = port.企业基本信息ID;
                    master.letportId = port.ID;
                    DateTime time = datatime.Value;
                    master.monitorTime = time;
                    //todo:主污染物可以在此增加
                    if (codes.Contains("B01")||codes.Contains("w00000"))
                    {
                        master.contamTypeId = 2;
                        var rtd = Parser.GetDoubleByKey("B01-Cou", content);
                        if (codes.Contains("w00000")) rtd=Parser.GetDoubleByKey("w00000-Cou", content);
                        master.sum = rtd ?? 0;
                    }
                    else if (codes.Contains("B02")|| codes.Contains("a00000"))
                    {
                        master.contamTypeId = 1;
                        var rtd = Parser.GetDoubleByKey("B02-Cou", content);
                        if (codes.Contains("a00000")) rtd=Parser.GetDoubleByKey("a00000-Cou", content);
                        master.sum = rtd ?? 0;
                    }
                    else
                    {
                        master.sum = null;
                    }
                    master.rtd = 0;
                    var begin = new DateTime(time.Year, time.Month, time.Day, 0, 0, 0);
                    var end = begin.AddDays(1);
                    //todo:(1 == 2)可以灵活更改
                    var whereCause =
                        (1 == 1)
                        ?
                        "企业排口ID=" + port.ID + " and 监测时间>='" + begin.ToString("yyyy-MM-dd HH:mm:ss") + "' and 监测时间<'" + end.ToString("yyyy-MM-dd HH:mm:ss") + "'"
                        :
                        "企业排口ID=" + port.ID + " and 监测时间='" + time.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                    sql = Cmd2031Sqls.M_SELECT.Replace("_企业ID", "_" + eCode).Replace("{搜索条件}", whereCause);

                    
                    count = pCtx.Database.SqlQuery<int?>(sql).FirstOrDefault();

                    if (!count.HasValue || count < 1)
                    {
                        sql = Cmd2031Sqls.M_INSERT
                              .Replace("_企业ID", "_" + eCode)
                              .Replace("{企业排口ID}", "" + master.letportId)
                              .Replace("{监测时间}", "'" + master.monitorTime.ToString("yyyy-MM-dd HH:mm:ss") + "'")
                              .Replace("{污染物类别ID}", "" + master.contamTypeId)
                              .Replace("{时段量}", master.sum.HasValue ? "" + master.sum : "null");

                        pCtx.Database.ExecuteSqlCommand(sql);
                    }
                    else
                    {
                        sql = Cmd2031Sqls.M_UPDATE
                            .Replace("_企业ID", "_" + eCode)
                            .Replace("{企业排口ID}", "" + master.letportId)
                            .Replace("{监测时间}", "'" + master.monitorTime.ToString("yyyy-MM-dd HH:mm:ss") + "'")
                            .Replace("{污染物类别ID}", "" + master.contamTypeId)
                            .Replace("{时段量}", master.sum.HasValue ? "" + master.sum : "null")
                            .Replace("{搜索条件}", whereCause);
                        
                        pCtx.Database.ExecuteSqlCommand(sql);
                    }
                    sql = Cmd2031Sqls.M_SELECT.Replace("_企业ID", "_" + eCode).Replace("{搜索条件}", whereCause).Replace("COUNT(1)", "ID");
                    
                    var masterId = pCtx.Database.SqlQuery<int?>(sql).FirstOrDefault();
                    if (!masterId.HasValue) return;

                    ProcessorHelper.RemoveMasterFactor(codes, true);

                    tableName = "从日数据_企业ID".Replace("_企业ID", "_" + eCode);
                    if (!ExistTable.Contains(tableName))
                    {
                        count = pCtx.Database.SqlQuery<int?>(Cmd2031Sqls.D_EXIST.Replace("_企业ID", "_" + eCode)).FirstOrDefault();
                        if (!count.HasValue || count < 1)
                        {
                            pCtx.Database.ExecuteSqlCommand(Cmd2031Sqls.D_CREATE.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2031Sqls.D_ALTER_1.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2031Sqls.D_ALTER_2.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2031Sqls.D_NONCLUSTERED_1.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2031Sqls.D_NONCLUSTERED_2.Replace("_企业ID", "_" + eCode));
                        }
                        ExistTable.Add(tableName);
                    }
                    Slave slave = new Slave();
                    slave.masterId = masterId.Value;

                    foreach (var code in codes)
                    {
                        var contam = CommonInformation.GetContamCode(code);
                        if (contam == null) continue;
                        slave.contamId = contam.ID;
                        var cou = Parser.GetDoubleByKey(code + "-Cou", content);
                        slave.cou = cou.HasValue ? cou.Value : 0;
                        slave.zsCou = Parser.GetDoubleByKey(code + "-ZsCou", content);
                        slave.min = Parser.GetDoubleByKey(code + "-Min", content);
                        slave.zsMin = Parser.GetDoubleByKey(code + "-ZsMin", content);
                        slave.avg = Parser.GetDoubleByKey(code + "-Avg", content);
                        slave.zsAvg = Parser.GetDoubleByKey(code + "-ZsAvg", content);
                        slave.max = Parser.GetDoubleByKey(code + "-Max", content);
                        slave.zsMax = Parser.GetDoubleByKey(code + "-ZsMax", content);
                        whereCause = "主日数据ID=" + slave.masterId + " and 污染物编码ID=" + slave.contamId;
                        sql = Cmd2031Sqls.D_SELECT.Replace("_企业ID", "_" + eCode).Replace("{搜索条件}", whereCause);
                        
                        count = pCtx.Database.SqlQuery<int?>(sql).FirstOrDefault();
                        if (!count.HasValue || count < 1)
                        {
                            sql = Cmd2031Sqls.D_INSERT
                                  .Replace("_企业ID", "_" + eCode)
                                  .Replace("{主日数据ID}", "" + slave.masterId)
                                  .Replace("{污染物编码ID}", "" + slave.contamId)
                                  .Replace("{Cou}", "" + slave.cou)
                                  .Replace("{ZSCou}", slave.zsCou.HasValue ? "" + slave.zsCou : "null")
                                  .Replace("{Min}", slave.min.HasValue ? "" + slave.min :"null")
                                  .Replace("{ZSMin}", slave.zsMin.HasValue ? "" + slave.zsMin : "null")
                                  .Replace("{Avg}", slave.avg.HasValue ? "" + slave.avg : "null")
                                  .Replace("{ZSAvg}", slave.zsAvg.HasValue ? "" + slave.zsAvg : "null")
                                  .Replace("{Max}", slave.max.HasValue ? "" + slave.max : "null")
                                  .Replace("{ZSMax}", slave.zsMax.HasValue ? "" + slave.zsMax : "null");
                            
                            pCtx.Database.ExecuteSqlCommand(sql);
                        }
                        else
                        {
                            sql = Cmd2031Sqls.D_UPDATE
                                .Replace("_企业ID", "_" + eCode)
                                .Replace("{主日数据ID}", "" + slave.masterId)
                                .Replace("{污染物编码ID}", "" + slave.contamId)
                                .Replace("{Cou}", "" + slave.cou)
                                .Replace("{ZSCou}", slave.zsCou.HasValue ? "" + slave.zsCou : "null")
                                .Replace("{Min}", slave.min.HasValue ? "" + slave.min : "null")
                                .Replace("{ZSMin}", slave.zsMin.HasValue ? "" + slave.zsMin : "null")
                                .Replace("{Avg}", slave.avg.HasValue ? "" + slave.avg : "null")
                                .Replace("{ZSAvg}", slave.zsAvg.HasValue ? "" + slave.zsAvg : "null")
                                .Replace("{Max}", slave.max.HasValue ? "" + slave.max : "null")
                                .Replace("{ZSMax}", slave.zsMax.HasValue ? "" + slave.zsMax : "null")
                                .Replace("{搜索条件}", whereCause);
                            
                            pCtx.Database.ExecuteSqlCommand(sql);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(sql + Environment.NewLine + ex + Environment.NewLine + content);
            }
            Log.Info("处理开始：2031->日数据(每个企业一套日主从表).");
        }
        public static void ProcessToCommonTable(string content)
        {
            Log.Info("处理开始：2031->日数据(所有企业一套日主从表).");
            try
            {
                if (ProcessorHelper.IsLossInfoOfCmd(content, out var mn, out var datatime, out var port, out var codes))
                {
                    return;
                }

                using (var pCtx = new PlatformXpfContext())
                {

                    Master master = new Master {enterpriseId = port.企业基本信息ID, letportId = port.ID};
                    DateTime time = datatime.Value;
                    master.monitorTime = time;
                    //todo:主污染物可以在此增加
                    if (codes.Contains("B01") || codes.Contains("w00000"))
                    {
                        master.contamTypeId = 2;
                        master.sum = codes.Contains("B01") ? Parser.GetDoubleByKey("B01-Cou", content) : Parser.GetDoubleByKey("w00000-Cou", content);

                    }
                    else if (codes.Contains("B02") || codes.Contains("a00000"))
                    {
                        master.contamTypeId = 1;
                        master.sum = codes.Contains("B02") ? Parser.GetDoubleByKey("B02-Cou", content) : Parser.GetDoubleByKey("a00000-Cou", content);

                    }
                    else
                    {
                        master.contamTypeId = 2;
                        master.sum = null;
                    }
                    master.rtd = null;
                    var begin = new DateTime(time.Year, time.Month, time.Day, 0, 0, 0);
                    var end = begin.AddDays(1);

                    var masterRecord = pCtx
                          .主日数据
                          .Where(t => t.企业排口ID == port.ID)
                          .Where(t => t.监测时间 >= begin)
                          .FirstOrDefault(t => t.监测时间 < end);
                    if (masterRecord == null)
                    {
                        masterRecord = new 主日数据();
                        masterRecord.企业基本信息ID = port.企业基本信息ID;
                        masterRecord.企业排口ID = master.letportId;
                        pCtx.主日数据.Add(masterRecord);
                    }
                    masterRecord.监测时间 = master.monitorTime;
                    masterRecord.污染物类别ID = master.contamTypeId;
                    masterRecord.时段量 = master.sum;
                    pCtx.SaveChanges();

                    ProcessorHelper.RemoveMasterFactor(codes, true);

                    Slave slave = new Slave();
                    slave.masterId = masterRecord.ID;

                    foreach (var code in codes)
                    {
                        var contam = CommonInformation.GetContamCode(code);
                        if (contam == null) continue;
                        slave.contamId = contam.ID;
                        var cou = Parser.GetDoubleByKey(code + "-Cou", content);
                        slave.cou = cou ?? 0;
                        slave.zsCou = Parser.GetDoubleByKey(code + "-ZsCou", content);
                        slave.min = Parser.GetDoubleByKey(code + "-Min", content);
                        slave.zsMin = Parser.GetDoubleByKey(code + "-ZsMin", content);
                        slave.avg = Parser.GetDoubleByKey(code + "-Avg", content);
                        slave.zsAvg = Parser.GetDoubleByKey(code + "-ZsAvg", content);
                        slave.max = Parser.GetDoubleByKey(code + "-Max", content);
                        slave.zsMax = Parser.GetDoubleByKey(code + "-ZsMax", content);

                        var slaveRecord = pCtx
                            .从日数据
                            .Where(t => t.主日数据ID == slave.masterId)
                            .FirstOrDefault(t => t.污染物编码ID == slave.contamId);
                        if (slaveRecord == null)
                        {
                            slaveRecord = new 从日数据();
                            slaveRecord.主日数据ID = slave.masterId;
                            slaveRecord.污染物编码ID = slave.contamId;

                            pCtx.从日数据.Add(slaveRecord);
                        }
                        slaveRecord.Cou = slave.cou;
                        slaveRecord.ZSCou = slave.zsCou;
                        slaveRecord.Avg = slave.avg;
                        slaveRecord.ZSAvg = slave.zsAvg;
                        slaveRecord.Min = slave.min;
                        slaveRecord.ZSMin = slave.zsMin;
                        slaveRecord.Max = slave.max;
                        slaveRecord.ZSMax = slave.zsMax;
                        pCtx.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex+Environment.NewLine+content);
            }
            Log.Info("处理开始：2031->日数据(所有企业一套日主从表).");
        }

        public static void SumToMonthFromDay(string content)
        {

            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrWhiteSpace(mn)) return;
                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue) return;
                var port = CommonInformation.GetLetportByMn(mn);
                if (port == null) return;

                using (var pCtx = new PlatformXpfContext())
                {
                    var codes = Parser.GetPollutantCodes(content);
                    if (codes == null) return;
                    Master master = new Master();
                    master.enterpriseId = port.企业基本信息ID;
                    master.letportId = port.ID;
                    DateTime time = datatime.Value;
                    master.monitorTime = time;
                    //todo:主污染物可以在此增加
                    if (codes.Contains("B01") || codes.Contains("w00000"))
                    {
                        master.contamTypeId = 2;
                        var rtd = Parser.GetDoubleByKey("B01-Cou", content);
                        if (!rtd.HasValue) Parser.GetDoubleByKey("w00000-Cou", content);
                        master.sum = rtd ?? 0;
                    }
                    else if (codes.Contains("B02") || codes.Contains("a00000"))
                    {
                        master.contamTypeId = 1;
                        var rtd = Parser.GetDoubleByKey("B02-Cou", content);
                        if (!rtd.HasValue) Parser.GetDoubleByKey("a00000-Cou", content);
                        master.sum = rtd ?? 0;
                    }
                    master.rtd = 0;
                    var begin = new DateTime(time.Year, time.Month, 1, 0, 0, 0);
                    var end = begin.AddMonths(1);

                    var masterRecord = pCtx
                          .主月数据
                          .Where(t => t.企业基本信息ID == port.企业基本信息ID)
                          .Where(t => t.企业排口ID == port.ID)
                          .Where(t => t.监测时间 >= begin)
                          .FirstOrDefault(t => t.监测时间 < end);
                    if (masterRecord == null)
                    {
                        masterRecord = new 主月数据();
                        masterRecord.企业基本信息ID = port.企业基本信息ID;
                        masterRecord.企业排口ID = port.ID;
                        pCtx.主月数据.Add(masterRecord);
                    }
                    masterRecord.监测时间 = master.monitorTime;
                    masterRecord.污染物类别ID = master.contamTypeId;
                    var masterDaysInMonth = pCtx
                        .主日数据
                        .Where(t => t.企业排口ID == port.ID)
                        .Where(t => t.监测时间 >= begin)
                        .Where(t => t.监测时间 < end)
                        .ToList();
                    masterRecord.时段量 = masterDaysInMonth.Count > 1 ? masterDaysInMonth.Where(t => t.时段量 != null).Sum(t => t.时段量) : 0;
                    pCtx.SaveChanges();
                    var ids = masterDaysInMonth.Select(t => t.ID).ToList();

                    ProcessorHelper.RemoveMasterFactor(codes, true);

                    foreach (var code in codes)
                    {
                        var contam = CommonInformation.GetContamCode(code);
                        if (contam == null) continue;

                        var slaveRecord = pCtx
                            .从月数据
                            .Where(t => t.主月数据ID == masterRecord.ID)
                            .FirstOrDefault(t => t.污染物编码ID == contam.ID);

                        if (slaveRecord == null)
                        {
                            slaveRecord = new 从月数据();
                            slaveRecord.主月数据ID = masterRecord.ID;
                            slaveRecord.污染物编码ID = contam.ID;

                            pCtx.从月数据.Add(slaveRecord);
                        }

                        var slaveDaysInMonth = pCtx
                            .从日数据
                            .Where(t => ids.Contains(t.ID))
                            .Where(t => t.污染物编码ID == contam.ID).ToList();

                        slaveRecord.Cou = slaveDaysInMonth.Count > 0 ? slaveDaysInMonth.Sum(t => t.Cou) : 0;
                        var list = slaveDaysInMonth.Where(t => t.ZSCou != null).ToList();
                        slaveRecord.ZSCou = list.Count > 0 ? list.Sum(t => t.ZSCou) : null;
                        list = slaveDaysInMonth.Where(t => t.Avg != null).ToList();
                        slaveRecord.Avg = list.Count > 0 ? list.Average(t => t.Avg) : null;
                        list = slaveDaysInMonth.Where(t => t.ZSAvg != null).ToList();
                        slaveRecord.ZSAvg = list.Count > 0 ? list.Average(t => t.ZSAvg) : null;

                        list = slaveDaysInMonth.Where(t => t.Min != null).ToList();
                        slaveRecord.Min = list.Count > 0 ? list.Min(t => t.Min) : null;
                        list = slaveDaysInMonth.Where(t => t.ZSMin != null).ToList();
                        slaveRecord.ZSMin = list.Count > 0 ? list.Min(t => t.ZSMin) : null;

                        list = slaveDaysInMonth.Where(t => t.Max != null).ToList();
                        slaveRecord.Max = list.Count > 0 ? list.Max(t => t.Max) : null;
                        list = slaveDaysInMonth.Where(t => t.ZSMax != null).ToList();
                        slaveRecord.ZSMax = list.Count > 0 ? list.Max(t => t.ZSMax) : null;

                        pCtx.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex + Environment.NewLine + content);
            }
        }

        public static void SumToYearFromDay(string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrWhiteSpace(mn)) return;
                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue) return;
                var port = CommonInformation.GetLetportByMn(mn);
                if (port == null) return;

                using (var pCtx = new PlatformXpfContext())
                {
                    var codes = Parser.GetPollutantCodes(content);
                    if (codes == null) return;
                    Master master = new Master();
                    master.enterpriseId = port.企业基本信息ID;
                    master.letportId = port.ID;
                    DateTime time = datatime.Value;
                    master.monitorTime = time;
                    //todo:主污染物可以在此增加
                    if (codes.Contains("B01") || codes.Contains("w00000"))
                    {
                        master.contamTypeId = 2;
                        var rtd = Parser.GetDoubleByKey("B01-Cou", content);
                        if (!rtd.HasValue) Parser.GetDoubleByKey("w00000-Cou", content);
                        master.sum = rtd ?? 0;
                    }
                    else if (codes.Contains("B02") || codes.Contains("a00000"))
                    {
                        master.contamTypeId = 1;
                        var rtd = Parser.GetDoubleByKey("B02-Cou", content);
                        if (!rtd.HasValue) Parser.GetDoubleByKey("a00000-Cou", content);
                        master.sum = rtd ?? 0;
                    }
                    master.rtd = 0;
                    var begin = new DateTime(time.Year, 1, 1, 0, 0, 0);
                    var end = begin.AddYears(1);

                    var masterRecord = pCtx
                          .主年数据
                          .Where(t => t.企业排口ID == port.ID)
                          .Where(t => t.监测时间 >= begin)
                          .FirstOrDefault(t => t.监测时间 < end);
                    if (masterRecord == null)
                    {
                        masterRecord = new 主年数据();
                        masterRecord.企业基本信息ID = port.企业基本信息ID;
                        masterRecord.企业排口ID = port.ID;
                        pCtx.主年数据.Add(masterRecord);
                    }
                    masterRecord.监测时间 = master.monitorTime;
                    masterRecord.污染物类别ID = master.contamTypeId;
                    var masterDaysInMonth = pCtx
                        .主日数据
                        .Where(t => t.企业排口ID == port.ID)
                        .Where(t => t.监测时间 >= begin)
                        .Where(t => t.监测时间 < end)
                        .ToList();
                    masterRecord.时段量 = masterDaysInMonth.Count > 1 ? masterDaysInMonth.Where(t => t.时段量 != null).Sum(t => t.时段量).Value : 0;
                    pCtx.SaveChanges();
                    var ids = masterDaysInMonth.Select(t => t.ID).ToList();

                    ProcessorHelper.RemoveMasterFactor(codes, true);

                    foreach (var code in codes)
                    {
                        var contam = CommonInformation.GetContamCode(code);
                        if (contam == null) continue;

                        var slaveRecord = pCtx
                            .从年数据
                            .Where(t => t.主年数据ID == masterRecord.ID)
                            .FirstOrDefault(t => t.污染物编码ID == contam.ID);

                        if (slaveRecord == null)
                        {
                            slaveRecord = new 从年数据();
                            slaveRecord.主年数据ID = masterRecord.ID;
                            slaveRecord.污染物编码ID = contam.ID;

                            pCtx.从年数据.Add(slaveRecord);
                        }

                        var slaveDaysInMonth = pCtx
                            .从日数据
                            .Where(t => ids.Contains(t.ID))
                            .Where(t => t.污染物编码ID == contam.ID).ToList();

                        slaveRecord.Cou = slaveDaysInMonth.Count > 0 ? slaveDaysInMonth.Sum(t => t.Cou) : 0;
                        var list = slaveDaysInMonth.Where(t => t.ZSCou != null).ToList();
                        slaveRecord.ZSCou = list.Count > 0 ? list.Sum(t => t.ZSCou) : null;
                        list = slaveDaysInMonth.Where(t => t.Avg != null).ToList();
                        slaveRecord.Avg = list.Count > 0 ? list.Average(t => t.Avg) : null;
                        list = slaveDaysInMonth.Where(t => t.ZSAvg != null).ToList();
                        slaveRecord.ZSAvg = list.Count > 0 ? list.Average(t => t.ZSAvg) : null;

                        list = slaveDaysInMonth.Where(t => t.Min != null).ToList();
                        slaveRecord.Min = list.Count > 0 ? list.Min(t => t.Min) : null;
                        list = slaveDaysInMonth.Where(t => t.ZSMin != null).ToList();
                        slaveRecord.ZSMin = list.Count > 0 ? list.Min(t => t.ZSMin) : null;

                        list = slaveDaysInMonth.Where(t => t.Max != null).ToList();
                        slaveRecord.Max = list.Count > 0 ? list.Max(t => t.Max) : null;
                        list = slaveDaysInMonth.Where(t => t.ZSMax != null).ToList();
                        slaveRecord.ZSMax = list.Count > 0 ? list.Max(t => t.ZSMax) : null;

                        pCtx.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                Log.Error(content);
            }
        }

    }
}
